package com.springbootxuexi.service;

import com.springbootxuexi.domain.Student;
import com.springbootxuexi.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StudentService {

    @Autowired
    private StudentRepository repository;

    public int login(Student student){

       int ret = 0;
        Student student1 = this.repository.findByAccount(student.getAccount());
        if(student1==null){
            ret = -1;
            return ret;
        }else{
            student1=null;
            student1 = this.repository.findByAccountAndPassword(student.getAccount(),student.getPassword());
            if(student1==null){
                ret = -2;
                return ret;
            }else{
                ret = student1.getId();
                return ret;
            }
        }
    }


    public int save(Student student){
        int ret = 0;
        Student student1 = this.repository.findByAccount(student.getAccount());
        if(student1!=null){
            ret = -1;
            return ret;
        }else {
            this.repository.save(student);
            return ret;
        }

    }

    public int update(Student student){
        int ret = 0;
        Student student1 = this.repository.findById(student.getId());
        if(student1==null){
            ret = -1;
            return ret;
        }else {
            this.repository.save(student);
            return ret;
        }

    }

    public List<Student> findall(){

        List<Student> students = this.repository.findAll();

        return students;
    }

    public Student findOne(Integer id){
        return this.repository.findOne(id);
    }

    public Map<String,String> delete(Integer id){
        Map<String,String> ret = new HashMap<String, String>();
        if(this.findOne(id)==null){
            ret.put("detail","要删除的人不存在");
            ret.put("code","1");
        }
        else
        {
            this.repository.delete(id);
            ret.put("detail","已经删除学号为"+id+"的学生");
            ret.put("code","0");
        }

        return ret;
    }

    public long count(){
        return this.repository.count();
    }

}
